package cn.itcast.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.context.BaseContext;
import cn.itcast.exception.AddressBookBusinessException;
import cn.itcast.exception.OrderBusinessException;
import cn.itcast.exception.ShoppingCartBusinessException;
import cn.itcast.mapper.AddressBookMapper;
import cn.itcast.mapper.OrderDetailMapper;
import cn.itcast.mapper.OrderMapper;
import cn.itcast.properties.ShopProperties;
import cn.itcast.result.PageBean;
import cn.itcast.service.OrderService;
import cn.itcast.utils.BMapUtil;
import cn.itcast.utils.WeChatPayUtil;
import cn.itheima.feign.ShoppingCartClient;
import cn.itheima.feign.UserClient;
import cn.itheima.orders.dto.OrdersPageQueryDTO;
import cn.itheima.orders.dto.OrdersPaymentDTO;
import cn.itheima.orders.dto.OrdersSubmitDTO;
import cn.itheima.orders.pojo.AddressBook;
import cn.itheima.orders.pojo.OrderDetail;
import cn.itheima.orders.pojo.Orders;
import cn.itheima.orders.vo.*;
import cn.itheima.shoppingcart.dto.ShoppingCartDTO;
import cn.itheima.shoppingcart.pojo.ShoppingCart;
import cn.itheima.sys.vo.BusinessDataVO;
import cn.itheima.sys.vo.SalesTop10ReportVO;
import cn.itheima.sys.vo.TurnoverReportVO;
import cn.itheima.users.pojo.User;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Service
@Slf4j
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;
    private OrderDetailMapper orderDetailMapper;
    private ShoppingCartClient shoppingCartClient;
    private AddressBookMapper addressBookMapper;
    private UserClient userClient;
    private WeChatPayUtil weChatPayUtil;
    private BMapUtil bMapUtil;
    private ShopProperties shopProperties;

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO 搜索条件
     * @return 无
     */
    @Override
    public PageBean pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.listWithDetail(ordersPageQueryDTO);

        page.getResult().forEach(dish -> {
            StringBuilder dishNames = new StringBuilder();
            dish.getOrderDetailList().forEach(dishDetail -> dish.setOrderDishes(dishNames.append(dishDetail.getName()).append("*").append(dishDetail.getNumber()).append(";").toString()));
        });

        return new PageBean(page.getTotal(), page.getResult());
    }

    /**
     * 完成订单
     *
     * @param id 订单id
     */
    @Override
    public void complete(Long id) {
        Orders order = orderMapper.getById(id);

        //判断订单状态是不是配送中
        if (!Objects.equals(order.getStatus(), Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.COMPLETED);

        orderMapper.update(order);
    }

    /**
     * 拒绝订单
     *
     * @param orders 订单信息
     */
    @Override
    public void rejection(Orders orders) {
        Orders order = orderMapper.getById(orders.getId());

        if (!Objects.equals(order.getStatus(), Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 拒单就是商家取消订单
        order.setStatus(Orders.CANCELLED);
        order.setRejectionReason(orders.getRejectionReason());
        orderMapper.update(order);
    }

    /**
     * 接单
     *
     * @param orders 订单id
     */
    @Override
    public void confirm(Orders orders) {
        Orders order = orderMapper.getById(orders.getId());

        if (!Objects.equals(order.getStatus(), Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.CONFIRMED);
        orderMapper.update(order);
    }

    /**
     * 派送订单
     *
     * @param id 订单id
     */
    @Override
    public void delivery(Long id) {
        Orders order = orderMapper.getById(id);

        if (!Objects.equals(order.getStatus(), Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    /**
     * @param ordersSubmitDTO 订单信息
     * @return 订单记录信息
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //异常情况的处理（收货地址为空、超出配送范围、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        String receiptAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        boolean addressOutofBound = bMapUtil.isAddressOutofBound(receiptAddress, shopProperties.getShopAddress());

        if (addressOutofBound) {
            throw new OrderBusinessException(MessageConstant.OUT_OF_BOUND);
        }

        Long userId = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartClient.list(userId).getData();
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            return orderDetail;
        }).collect(Collectors.toList());

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartClient.clean(userId);

        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO 订单支付
     * @return 预支付的信息
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userClient.getById(userId).getData();

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal("0.01"), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 支付成功回调
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 1);
        jsonObject.put("orderId", ordersDB.getId());
        jsonObject.put("content", orders.getNumber());
//        webSocketServer.sendToAllClient(jsonObject.toJSONString());

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO 订单分页查询条件
     * @return 订单列表
     */
    @Override
    public PageBean getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {

        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> orders = orderMapper.listWithDetail(ordersPageQueryDTO);

        return new PageBean(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据id查询订单详情
     *
     * @param id 订单id
     * @return 订单详情
     */
    @Override
    public OrderVO getDetailById(Long id) {
        return orderMapper.getDetailById(id);
    }

    /**
     * 取消订单
     *
     * @param order 订单信息
     */
    @Override
    public void cancel(Orders order) {
        Orders orderEntity = orderMapper.getById(order.getId());

        //  1. 校验订单是否存在
        if (orderEntity == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //  2. 仅待付款和待接单状态的订单可以直接取消
        if (orderEntity.getStatus().equals(Orders.CANCELLED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态改为退款
        if (orderEntity.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //weChatUtil.refund()
            order.setPayStatus(Orders.REFUND);
        }

        order.setStatus(Orders.CANCELLED);
        order.setCancelReason(MessageConstant.USER_CANCEL);
        order.setCancelTime(LocalDateTime.now());

        orderMapper.update(order);
    }

    /**
     * 再来一单
     *
     * @param id 订单id
     */
    @Override
    @Transactional
    public void repetition(Long id) {
        //1、先拿到当前订单的明细
        OrderVO orderDetail = orderMapper.getDetailById(id);

        //2、将明细添加到当前用户的购物车
        orderDetail.getOrderDetailList().forEach(od -> {

            ShoppingCartDTO cart = new ShoppingCartDTO();
            BeanUtils.copyProperties(od, cart);

            shoppingCartClient.add(cart);
        });
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return 获取统计接口
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        return orderMapper.getCountByStatus();
    }

    /**
     * 用户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 2);
        jsonObject.put("orderId", id);
        jsonObject.put("content", "用户催单了,订单号为:" + orders.getNumber());
        log.info(jsonObject.toJSONString());
//        webSocketServer.sendToAllClient(jsonObject.toJSONString());
    }

    @Override
    public List<TurnoverReportVO> getSumByDate(LocalDate begin, LocalDate end) {
        return orderMapper.getSumByDate(begin, end);
    }

    @Override
    public Integer countByMap(Map<String, Object> map) {
        return orderMapper.countByMap(map);
    }

    @Override
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        return orderMapper.getBusinessData(begin, end);
    }

    @Override
    public List<BusinessDataVO> getBusinessListData(LocalDateTime begin, LocalDateTime end) {
        return orderMapper.getBusinessListData(begin, end);
    }

    @Override
    public List<SalesTop10ReportVO> countDishAndSetmealByTime(LocalDate begin, LocalDate end) {
        return orderMapper.countDishAndSetmealByTime(begin, end);
    }

    @Override
    public OrderOverViewVO getAllCountByStatus(LocalDateTime start, LocalDateTime end) {
        return orderMapper.getAllCountByStatus(start, end);
    }
}